<template>
  <div v-if="visible" class="dialog-overlay" @click="handleOverlayClick">
    <div
      class="dialog-content"
      @click.stop
      @dragenter="handleGlobalDragEnter"
      @dragover="handleGlobalDragOver"
      @dragleave="handleGlobalDragLeave"
      @drop="handleGlobalDrop"
    >
      <div class="dialog-header">
        <div class="header-content">
          <div v-if="currentBatch" class="batch-logo">
            <img
              :src="getBrandLogo(currentBatch.brand_name)"
              :alt="currentBatch.brand_name"
              class="brand-logo-img"
            />
          </div>
          <h3>导入数据</h3>
        </div>
        <button class="close-btn" @click="handleClose">
          <XIcon :size="16" />
        </button>
      </div>

      <div class="dialog-body">
        <div class="upload-sections">
          <div class="upload-section">
            <h4>图片包上传</h4>
            <div
              class="upload-area"
              :class="{
                'drag-over': dragOverImage,
                'has-file': imageFile,
              }"
              @drop="handleImageDrop"
              @click="triggerImageUpload"
            >
              <input
                ref="imageInput"
                type="file"
                accept=".zip"
                @change="handleImageFileSelect"
                style="display: none"
              />
              <div class="upload-content">
                <UploadIcon :size="32" />
                <p v-if="!imageFile">点击或拖拽ZIP文件到此处</p>
                <p v-else class="file-name">{{ imageFile.name }}</p>
                <p class="upload-hint">支持ZIP格式的图片包</p>
              </div>
            </div>
          </div>

          <div class="upload-section">
            <h4>商品信息上传</h4>
            <div
              class="upload-area"
              :class="{
                'drag-over': dragOverExcel,
                'has-file': excelFile,
              }"
              @drop="handleExcelDrop"
              @click="triggerExcelUpload"
            >
              <input
                ref="excelInput"
                type="file"
                accept=".txt,.xlsx,.xls,.csv"
                @change="handleExcelFileSelect"
                style="display: none"
              />
              <div class="upload-content">
                <UploadIcon :size="32" />
                <p v-if="!excelFile">点击或拖拽文件到此处</p>
                <p v-else class="file-name">{{ excelFile.name }}</p>
                <p class="upload-hint">支持文本文件、XLSX、XLS、CSV格式</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 拖拽展开的覆盖层 -->
        <div
          v-if="isExpanding || isCollapsing"
          class="drag-overlay"
          :class="{ collapsing: isCollapsing }"
          :style="{
            '--expand-center-x': expandCenter.x + 'px',
            '--expand-center-y': expandCenter.y + 'px',
          }"
        >
          <div class="drag-overlay-content">
            <UploadIcon :size="48" />
            <p class="drag-overlay-title">释放文件以上传</p>
            <p class="drag-overlay-hint">支持ZIP、文本文件、XLSX、XLS、CSV格式</p>
          </div>
        </div>

        <div class="import-mode-section">
          <h4>导入模式</h4>
          <div class="import-mode-options">
            <label class="radio-option">
              <input type="radio" v-model="importMode" value="overwrite" name="importMode" />
              <span class="radio-label"
                ><span class="clear-text">清空</span>全部数据并覆盖现有数据</span
              >
            </label>
            <label class="radio-option">
              <input type="radio" v-model="importMode" value="append" name="importMode" />
              <span class="radio-label">追加数据（保留现有数据）</span>
            </label>
            <label class="radio-option">
              <input type="radio" v-model="importMode" value="smart" name="importMode" />
              <span class="radio-label">
                <span class="clear-text">清空</span>未做向量化数据，并追加（保留
                <span class="status-capsule status-vectoring">向量中</span>
                和
                <span class="status-capsule status-completed">完成</span>
                数据）
              </span>
            </label>
          </div>
        </div>

        <div class="upload-requirement">
          <p class="requirement-text">
            <span class="required-mark">*</span>
            需要同时上传图片包和商品信息文件才能开始上传
          </p>
        </div>
      </div>

      <div class="dialog-footer">
        <button class="btn btn-secondary" @click="handleCancel">取消</button>
        <button class="btn btn-primary" :disabled="!canStartUpload" @click="handleStartUpload">
          开始上传
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { XIcon, UploadIcon } from './icons'
import { generateLogoPlaceholder } from '../utils/logoPlaceholder'

export default {
  name: 'ImportDialog',
  components: {
    XIcon,
    UploadIcon,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    batchId: {
      type: [String, Number],
      default: '',
    },
    currentBatch: {
      type: Object,
      default: null,
    },
    brands: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['close', 'cancel', 'start-upload'],
  setup(props, { emit }) {
    const imageInput = ref(null)
    const excelInput = ref(null)
    const imageFile = ref(null)
    const excelFile = ref(null)
    const dragOverImage = ref(false)
    const dragOverExcel = ref(false)
    const isExpanding = ref(false) // 控制展开动画
    const isCollapsing = ref(false) // 控制收缩动画
    const expandCenter = ref({ x: 0, y: 0 }) // 展开中心点
    const importMode = ref('append') // 默认选择追加模式

    // 获取品牌LOGO
    const getBrandLogo = brandName => {
      const brand = props.brands.find(b => b.name === brandName)
      return brand && brand.logo ? brand.logo : generateLogoPlaceholder(brandName)
    }

    // 计算是否可以开始上传
    const canStartUpload = computed(() => {
      return imageFile.value && excelFile.value
    })

    // 触发文件选择
    const triggerImageUpload = () => {
      imageInput.value?.click()
    }

    const triggerExcelUpload = () => {
      excelInput.value?.click()
    }

    // 处理文件选择
    const handleImageFileSelect = event => {
      const file = event.target.files[0]
      if (file && (file.type === 'application/zip' || file.name.toLowerCase().endsWith('.zip'))) {
        imageFile.value = file
      } else {
        alert('请选择ZIP格式的文件')
      }
    }

    const handleExcelFileSelect = event => {
      const file = event.target.files[0]
      if (
        file &&
        (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel' ||
          file.type === 'text/csv' ||
          file.type === 'text/plain' ||
          file.name.toLowerCase().endsWith('.xlsx') ||
          file.name.toLowerCase().endsWith('.xls') ||
          file.name.toLowerCase().endsWith('.csv') ||
          file.name.toLowerCase().endsWith('.txt'))
      ) {
        excelFile.value = file
      } else {
        alert('请选择文本文件、Excel或CSV格式的文件')
      }
    }

    // 全局拖拽进入处理
    const handleGlobalDragEnter = event => {
      event.preventDefault()

      // 检查是否有文件
      const hasFiles = event.dataTransfer.types.includes('Files')

      if (hasFiles) {
        // 计算两个上传框的中心点
        calculateExpandCenter()
        // 开始展开动画
        startExpandAnimation()
      }
    }

    // 全局拖拽处理 - 保持展开状态
    const handleGlobalDragOver = event => {
      event.preventDefault()
      // 设置拖拽效果，告诉浏览器我们接受文件
      event.dataTransfer.dropEffect = 'copy'
    }

    // 全局drop处理
    const handleGlobalDrop = event => {
      event.preventDefault()
      const files = event.dataTransfer.files

      if (files.length > 0) {
        let hasImageFile = false
        let hasExcelFile = false

        // 处理多个文件
        for (let i = 0; i < files.length; i++) {
          const file = files[i]
          const fileName = file.name.toLowerCase()

          // 判断文件类型
          const isImageFile = fileName.endsWith('.zip')
          const isExcelFile =
            fileName.endsWith('.xlsx') ||
            fileName.endsWith('.xls') ||
            fileName.endsWith('.csv') ||
            fileName.endsWith('.txt')

          // 直接覆盖，不检查是否已存在
          if (isImageFile) {
            imageFile.value = file
            hasImageFile = true
          } else if (isExcelFile) {
            excelFile.value = file
            hasExcelFile = true
          } else {
            // 不支持的文件格式，显示提示但继续处理其他文件
            console.warn(`不支持的文件格式: ${fileName}`)
          }
        }

        // 根据处理的文件类型设置高亮
        if (hasImageFile && hasExcelFile) {
          // 如果两个文件都有，优先显示图片区域
          collapseToArea('image')
        } else if (hasImageFile) {
          collapseToArea('image')
        } else if (hasExcelFile) {
          collapseToArea('excel')
        }

        // 如果有不支持的文件，显示提示
        const hasUnsupportedFiles = Array.from(files).some(file => {
          const fileName = file.name.toLowerCase()
          return (
            !fileName.endsWith('.zip') &&
            !fileName.endsWith('.xlsx') &&
            !fileName.endsWith('.xls') &&
            !fileName.endsWith('.csv') &&
            !fileName.endsWith('.txt')
          )
        })

        if (hasUnsupportedFiles) {
          alert('部分文件格式不支持，仅支持ZIP、文本文件、XLSX、XLS、CSV格式')
        }
      }
    }

    const handleGlobalDragLeave = event => {
      event.preventDefault()

      // 检查是否真的离开了对话框区域
      // 只有当鼠标完全离开对话框时才停止展开动画
      const rect = event.currentTarget.getBoundingClientRect()
      const x = event.clientX
      const y = event.clientY

      // 如果鼠标还在对话框区域内，不停止动画
      if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
        return
      }

      stopExpandAnimation()
    }

    const handleImageDrop = event => {
      event.preventDefault()
      const files = event.dataTransfer.files
      if (files.length > 0) {
        const file = files[0]
        if (file.type === 'application/zip' || file.name.toLowerCase().endsWith('.zip')) {
          imageFile.value = file
          // 缩回到图片区域
          collapseToArea('image')
        } else {
          alert('请选择ZIP格式的文件')
          stopExpandAnimation()
        }
      }
    }

    const handleExcelDrop = event => {
      event.preventDefault()
      const files = event.dataTransfer.files
      if (files.length > 0) {
        const file = files[0]
        if (
          file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel' ||
          file.type === 'text/csv' ||
          file.name.toLowerCase().endsWith('.xlsx') ||
          file.name.toLowerCase().endsWith('.xls') ||
          file.name.toLowerCase().endsWith('.csv')
        ) {
          excelFile.value = file
          // 缩回到Excel区域
          collapseToArea('excel')
        } else {
          alert('请选择文本文件、Excel或CSV格式的文件')
          stopExpandAnimation()
        }
      }
    }

    // 处理按钮点击
    const handleOverlayClick = () => {
      resetState()
      emit('close')
    }

    const handleClose = () => {
      resetState()
      emit('close')
    }

    const handleCancel = () => {
      resetState()
      emit('cancel')
    }

    const handleStartUpload = () => {
      emit('start-upload', {
        imageFile: imageFile.value,
        excelFile: excelFile.value,
        batchId: props.batchId,
        importMode: importMode.value,
      })
      resetState()
    }

    // 计算展开中心点
    const calculateExpandCenter = () => {
      // 获取两个上传框的位置
      const imageArea = document.querySelector('.upload-area')
      const excelArea = document.querySelectorAll('.upload-area')[1]

      if (imageArea && excelArea) {
        const imageRect = imageArea.getBoundingClientRect()
        const excelRect = excelArea.getBoundingClientRect()

        // 计算两个框的中心点
        const centerX = (imageRect.left + imageRect.right + excelRect.left + excelRect.right) / 4
        const centerY = (imageRect.top + imageRect.bottom + excelRect.top + excelRect.bottom) / 4

        expandCenter.value = { x: centerX, y: centerY }
      }
    }

    // 开始展开动画
    const startExpandAnimation = () => {
      // 开始展开动画
      isExpanding.value = true
    }

    // 停止展开动画
    const stopExpandAnimation = () => {
      isExpanding.value = false
      isCollapsing.value = false
      dragOverImage.value = false
      dragOverExcel.value = false
    }

    // 缩回到指定区域
    const collapseToArea = area => {
      // 开始收缩动画
      isCollapsing.value = true
      isExpanding.value = false

      // 根据区域设置高亮
      if (area === 'image') {
        dragOverImage.value = true
        dragOverExcel.value = false
      } else if (area === 'excel') {
        dragOverExcel.value = true
        dragOverImage.value = false
      }

      // 0.4秒后完成收缩动画
      setTimeout(() => {
        isCollapsing.value = false
        // 再等0.4秒让高亮状态消失
        setTimeout(() => {
          dragOverImage.value = false
          dragOverExcel.value = false
        }, 400)
      }, 400)
    }

    // 重置状态
    const resetState = () => {
      imageFile.value = null
      excelFile.value = null
      dragOverImage.value = false
      dragOverExcel.value = false
      isExpanding.value = false
      isCollapsing.value = false
      expandCenter.value = { x: 0, y: 0 }
      importMode.value = 'append' // 重置为默认模式
      if (imageInput.value) imageInput.value.value = ''
      if (excelInput.value) excelInput.value.value = ''
    }

    return {
      imageInput,
      excelInput,
      imageFile,
      excelFile,
      dragOverImage,
      dragOverExcel,
      isExpanding,
      isCollapsing,
      expandCenter,
      importMode,
      canStartUpload,
      getBrandLogo,
      triggerImageUpload,
      triggerExcelUpload,
      handleImageFileSelect,
      handleExcelFileSelect,
      handleGlobalDragEnter,
      handleGlobalDragOver,
      handleGlobalDragLeave,
      handleGlobalDrop,
      handleImageDrop,
      handleExcelDrop,
      handleOverlayClick,
      handleClose,
      handleCancel,
      handleStartUpload,
      resetState,
    }
  },
}
</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: var(--border-radius);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch-logo {
  width: 32px;
  height: 32px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.brand-logo-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid var(--border-color);
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  color: var(--text-secondary);
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f5f5f5;
  color: var(--text-color);
}

.dialog-body {
  padding: 24px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
  min-height: 0;
}

.upload-sections {
  display: flex;
  gap: 16px;
  flex: 1;
  min-height: 0;
}

.upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.import-mode-section {
  flex-shrink: 0;
}

.upload-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
}

.upload-area {
  border: 2px dashed var(--border-color);
  border-radius: var(--border-radius);
  padding: 24px 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  background: #fafafa;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 120px;
}

.upload-area:hover {
  border-color: var(--primary-color);
  background: #f0f8ff;
}

.upload-area.drag-over {
  border-color: var(--primary-color);
  background: #e6f7ff;
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
  position: relative;
}

.upload-area.drag-over::before {
  content: '✓ 拖拽到此区域';
  position: absolute;
  top: -8px;
  left: 50%;
  transform: translateX(-50%);
  background: var(--primary-color);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  z-index: 10;
  animation: pulse 1.5s infinite;
}

/* 拖拽覆盖层样式 */
.drag-overlay {
  position: fixed;
  top: var(--expand-center-y, 50%);
  left: var(--expand-center-x, 50%);
  transform: translate(-50%, -50%);
  width: 80vw;
  height: 70vh;
  max-width: 700px;
  max-height: 500px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(10px);
  border: 3px dashed var(--primary-color);
  border-radius: var(--border-radius);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  animation: expand 0.4s ease-out forwards;
}

.drag-overlay.collapsing {
  animation: collapse 0.4s ease-in forwards;
}

.drag-overlay-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  text-align: center;
}

.drag-overlay-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--primary-color);
  margin: 0;
}

.drag-overlay-hint {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0;
}

@keyframes expand {
  0% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.1);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

@keyframes collapse {
  0% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
  100% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.1);
  }
}

@keyframes pulse {
  0% {
    transform: translateX(-50%) scale(1);
  }
  50% {
    transform: translateX(-50%) scale(1.05);
  }
  100% {
    transform: translateX(-50%) scale(1);
  }
}

.upload-area.has-file {
  border-color: var(--success-color);
  background: #f6ffed;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.upload-content p {
  margin: 0;
  font-size: 14px;
  color: var(--text-color);
}

.upload-content .file-name {
  font-weight: 600;
  color: var(--success-color);
}

.upload-content .upload-hint {
  font-size: 12px;
  color: var(--text-secondary);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid var(--border-color);
  background: #fafafa;
}

.btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-secondary {
  background: white;
  color: var(--text-color);
}

.btn-secondary:hover {
  background: #f5f5f5;
}

.btn-primary {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #40a9ff;
  border-color: #40a9ff;
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 导入模式选项样式 */
.import-mode-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.radio-option {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
  padding: 8px;
  border-radius: var(--border-radius);
  transition: background-color 0.2s;
}

.radio-option:hover {
  background-color: #f5f5f5;
}

.radio-option input[type='radio'] {
  margin: 0;
  margin-top: 2px;
  cursor: pointer;
}

.radio-label {
  font-size: 14px;
  color: var(--text-color);
  line-height: 1.4;
  flex: 1;
}

.clear-text {
  color: #ff4d4f;
  font-weight: bold;
}

/* 状态胶囊样式 */
.status-capsule {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  margin: 0 2px;
}

.status-vectoring {
  background-color: #722ed1;
}

.status-completed {
  background-color: #1890ff;
}

/* 上传要求提示样式 */
.upload-requirement {
  margin-top: 16px;
  padding: 12px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: var(--border-radius);
}

.requirement-text {
  margin: 0;
  font-size: 13px;
  color: #52c41a;
  display: flex;
  align-items: center;
  gap: 4px;
}

.required-mark {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-sections {
    flex-direction: column;
    gap: 16px;
  }

  .upload-area {
    min-height: 100px;
  }

  .dialog-content {
    width: 95%;
    max-width: 500px;
  }
}

@media (max-width: 480px) {
  .dialog-body {
    padding: 16px;
    gap: 16px;
  }

  .upload-sections {
    gap: 12px;
  }

  .upload-area {
    padding: 16px 12px;
    min-height: 80px;
  }

  .upload-content p {
    font-size: 13px;
  }

  .upload-hint {
    font-size: 11px;
  }
}
</style>
